package com.example.cart.providers;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.cart.CartApplication;
import com.example.cart.dto.Cart;
import com.example.cart.repository.CartDao;

public class GoodsContentProvider extends ContentProvider {


    public static final String Authorities = "com.example.cart.providers.GoodsContentProvider";
    private final int All = 1;
    private UriMatcher uriMatcher;
    private final int WithIdSuffix = 2;

    @Override
    public boolean onCreate() {

        Log.d("GoodsContentProvider","onCreate");

        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);


        uriMatcher.addURI(Authorities, "/goods", All);

        uriMatcher.addURI(Authorities, "/goods/#", WithIdSuffix);

        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        if(uriMatcher.match(uri)==All){
            return     CartApplication.get().getGoodsDataBase().cartDao().all();
        }
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return "";
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Cart param = new Cart();
        CartDao cartDao = CartApplication.get().getGoodsDataBase().cartDao();
        switch (uriMatcher.match(uri)) {
            case WithIdSuffix: {
                //content://com.example.cart.providers.GoodsContentProvider/goods
                // 根据id删除购物车

                param.setId(Integer.parseInt(uri.getLastPathSegment()));
                cartDao.delete(param);
                break;
            }
            case All:{
                //content://com.example.cart.providers.GoodsContentProvider/goods/123
                // 清空购物车
                cartDao.page(0,100).forEach(cart->{
                    param.setId(cart.getCartId());
                    cartDao.delete(param);
                });
            }
        }

        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }
}
